<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

abstract class BaseModel extends Model {


    public function makeSave() {

        return $this->save();
    }

    public function makeDelete() {
        return $this->forceDelete();
    }


    public static function updateByValues( $search, $params ) {
        $find = null;


        foreach ( $search as $key => $val ) {
            if ( $find == null ) {
                $find = ( new static )::where( $key, $val );
            } else {
                $find = $find->where( $key, $val );
            }
        }
        try {
            $find = $find->withTrashed();
        } catch ( \Exception $e ) {
            Log::info( $e->getMessage() );
        }
        $find = $find->first();
        if ( isset( $params["restore"] ) ) {
            $params["deleted_at"] = null;
        }
        $find->fill( $params );

        $find->makeSave();


        return $find;
    }

    public function delete() {

        return parent::delete();
    }

    protected function deleteFileByPath() {
        if ( $this->path != null && $this->path != "default" ) {
            $file = pathinfo( $this->path );
            File::delete( storage_path( "/app/public/files/{$file["filename"]}.".($file["extension"]??'') ) );
        }
    }


}
